package com.feishi.core.analytic.packing.encode;

import com.feishi.core.util.common.EncryptUtil;
import com.feishi.core.util.common.RSAUtils;

import java.io.ByteArrayOutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;

/**
 * Created by caixq on 6/26 026.
 */
public class EncodeRsaExecutor implements EncodeExecutor<EncodeRsaParam> {
    @Override
    public byte[] encode(byte[] bytes, EncodeRsaParam param) {
        RSAPublicKey key=param.getRsaPublicKey();
        try {
            return RSAUtils.encryptByPublicKey(bytes, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    @Override
    public byte[] decode(byte[] bytes, EncodeRsaParam param) {
        RSAPrivateKey priKey=param.getRsaPrivateKey();
        try {
            return RSAUtils.decryptByPrivateKey(bytes, priKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static void main(String[] args) throws Exception {
        HashMap<String, Object> map = RSAUtils.getKeys();
        RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
        RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

        //模
        String modulus = publicKey.getModulus().toString();
        //公钥指数
        String public_exponent = publicKey.getPublicExponent().toString();
        //私钥指数
        String private_exponent = privateKey.getPrivateExponent().toString();

        //使用模和指数生成公钥和私钥
        RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
        RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
        //加密后的密文




        ByteArrayOutputStream out=new ByteArrayOutputStream();

        for (int i = 0; i < 1000; i++) {
            out.write((int) (Math.random()*1000));
        }
        String data=EncryptUtil.getFormattedText(out.toByteArray());


        System.out.println(data);


        EncodeRsaParam param = new EncodeRsaParam(publicKey, privateKey);

        EncodeRsaExecutor executor=new EncodeRsaExecutor();
        System.out.println(new String(executor.decode(executor.encode(data.getBytes(),param),param)));








        String mi = EncryptUtil.getFormattedText(RSAUtils.encryptByPublicKey(data.getBytes(), pubKey));
        System.err.println(mi);
        //解密后的明文
        String ndata = RSAUtils.decryptByPrivateKey(mi, priKey);
        System.err.println(data);
        System.err.println(data.equals(ndata));
    }
}
